<template>
  <div class="ad-management">
    <el-container>
      <el-header>广告管理</el-header>
      <el-main>
        <el-card class="ad-card">
          <!-- 查询表单 -->
          <el-form :inline="true" class="query-form" @submit.native.prevent>
            <el-form-item label="标题">
              <el-input v-model="query.title" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchAds">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 表格 -->
          <el-table :data="adsTableData" class="ads-table" style="width: 100%">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="广告ID" width="80"></el-table-column>
            <el-table-column prop="title" label="标题"></el-table-column>
            <el-table-column prop="url" label="链接"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" @click="editAd(scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="deleteAd(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            class="pagination"
            layout="prev, pager, next"
            :total="totalAds"
            :page-size="pageSize"
            @current-change="handlePageChange"
          ></el-pagination>
        </el-card>

        <!-- 添加/编辑广告对话框 -->
        <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" width="50%">
          <el-form :model="adForm" :rules="formRules" ref="adForm">
            <el-form-item label="标题" prop="title">
              <el-input v-model="adForm.title"></el-input>
            </el-form-item>
            <el-form-item label="链接" prop="url">
              <el-input v-model="adForm.url"></el-input>
            </el-form-item>
            <el-form-item label="图片" prop="pic">
              <el-upload
                class="upload-demo"
                action=""
                :http-request="uploadFile"
                :before-upload="beforeUpload"
                list-type="picture-card"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-image v-if="adForm.pic" :src="adForm.pic" fit="cover" style="width: 100px; height: 100px;"></el-image>
            </el-form-item>
            <el-form-item label="类别">
              <el-select v-model="adForm.categoryId" placeholder="请选择类别">
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAdForm">确定</el-button>
          </div>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import axios from 'axios';

export default {
  name: 'AdManagement',
  setup() {
    const query = reactive({
      title: '',
    });

    const adsTableData = ref([]);
    const totalAds = ref(0);
    const pageSize = ref(10);
    const currentPage = ref(1);
    const dialogVisible = ref(false);
    const dialogTitle = ref('添加广告');
    const adForm = reactive({
      id: null,
      title: '',
      url: '',
      pic: '',
      categoryId: null,
    });
    const categories = ref([]);
    const formRules = {
      title: [
        { required: true, message: '请输入广告标题', trigger: 'blur' },
      ],
      url: [
        { required: true, message: '请输入广告链接', trigger: 'blur' },
      ],
      categoryId: [
        { required: true, message: '请选择广告类别', trigger: 'change' },
      ],
    };

    // 初始化类别数据（模拟）
    axios.get('/api/categories').then(response => {
      categories.value = response.data;
    });

    // 查询广告
    const searchAds = async () => {
      const response = await axios.post('/api/ads/search', {
        ...query,
        page: currentPage.value,
        size: pageSize.value,
      });
      adsTableData.value = response.data.list;
      totalAds.value = response.data.total;
    };

    // 重置查询
    const resetQuery = () => {
      query.title = '';
      currentPage.value = 1;
      searchAds();
    };

    // 分页处理
    const handlePageChange = (page) => {
      currentPage.value = page;
      searchAds();
    };

    // 编辑广告
    const editAd = (row) => {
      dialogTitle.value = '编辑广告';
      adForm.id = row.id;
      adForm.title = row.title;
      adForm.url = row.url;
      adForm.pic = row.pic;
      adForm.categoryId = row.categoryId;
      dialogVisible.value = true;
    };

    // 删除广告
    const deleteAd = async (row) => {
      const response = await axios.delete(`/api/ads/${row.id}`);
      if (response.data.success) {
        searchAds();
        ElMessage({
          message: '删除成功',
          type: 'success',
        });
      } else {
        ElMessage({
          message: '删除失败',
          type: 'error',
        });
      }
    };

    // 提交广告表单
    const submitAdForm = async () => {
      try {
        await axios.post('/api/ads/save', adForm);
        dialogVisible.value = false;
        searchAds();
        ElMessage({
          message: '保存成功',
          type: 'success',
        });
      } catch (error) {
        console.error(error);
        ElMessage({
          message: '保存失败',
          type: 'error',
        });
      }
    };

    // 上传文件
    const uploadFile = (request) => {
      const formData = new FormData();
      formData.append('file', request.file);
      axios.post('/api/upload', formData).then(response => {
        adForm.pic = response.data.url;
        request.onSuccess(response.data);
      }).catch(error => {
        request.onError(error);
      });
    };

    // 上传前校验
    const beforeUpload = (file) => {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        ElMessage.error('上传文件只能是图片!');
      }
      return isImage && isLt2M;